﻿using System;
using System.Collections.Generic;
using Icms.Core.Model;
using Icms.Core.Repository;
using Omu.ValueInjecter;

namespace Icms.Tests
{
    public class Fill : NoSourceValueInjection
    {
        private readonly IUniRepo u;

        private static long s;
        private static int i;
        private readonly bool isChild;

        public Fill(IUniRepo u, bool isChild = false)
        {
            this.u = u;
            this.isChild = isChild;
        }

        protected override void Inject(object target)
        {
            var props = target.GetProps();
            for (var j = 0; j < props.Count; j++)
            {
                var p = props[j];
                if (target.GetType() == typeof(Person) && (p.Name == "Gender" || p.Name == "Type"))
                {
                    p.SetValue(target, "f");
                }
                else if(target.GetType() == typeof(Ruling) && (p.Name == "Status"))
                {
                    p.SetValue(target, "D");
                }
                else if (p.Name == "EntityId") p.SetValue(target, Guid.NewGuid());
                else if (p.PropertyType == typeof(string)) p.SetValue(target, "a" + ++s);
                else if (p.PropertyType == typeof(int)) p.SetValue(target, ++i);
                else if (p.PropertyType == typeof(DateTime)) p.SetValue(target, DateTime.Now);
                else if (p.PropertyType.IsSubclassOf(typeof(Entity)) && p.PropertyType != target.GetType())
                {
                    Console.WriteLine("create " + p.PropertyType.Name);
                    dynamic o = Activator.CreateInstance(p.PropertyType).InjectFrom(new Fill(u, true));
                    u.Insert(o);
                    u.Save();
                    p.SetValue(target, o);
                }
                else if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) && !isChild)
                {
                    var t = p.PropertyType.GetGenericArguments()[0];
                    if (!t.IsSubclassOf(typeof(Entity))) continue;
                    
                    Console.WriteLine("create a list of " + t.Name);
                    var tlist = typeof(List<>).MakeGenericType(t);
                    dynamic list = Activator.CreateInstance(tlist);
                    for (var k = 0; k < 3; k++)
                    {
                        Console.WriteLine(" create " + t.Name);
                        dynamic o = Activator.CreateInstance(t).InjectFrom(new Fill(u, true));
                        u.Insert(o);
                        u.Save();
                        Console.WriteLine(" add " + t.Name +" to list");
                        list.Add(o);

                    }
                    p.SetValue(target, list);
                }
            }
        }
    }
}